package com.dongbo.recorder.screenrecord.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.coder.ffmpeg.call.CommonCallBack;
import com.coder.ffmpeg.jni.FFmpegCommand;
import com.coder.ffmpeg.utils.FFmpegUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.dongbo.recorder.screenrecord.R;
import com.dongbo.recorder.screenrecord.adapter.EditAdapter;
import com.dongbo.recorder.screenrecord.base.BaseActivity;
import com.dongbo.recorder.screenrecord.bean.EditVideoBean;
import com.dongbo.recorder.screenrecord.contents.Contents;
import com.dongbo.recorder.screenrecord.dialog.LoadingPop;
import com.dongbo.recorder.screenrecord.utils.FileUtils;
import com.dongbo.recorder.screenrecord.utils.eventbus.EventBusUtils;
import com.dongbo.recorder.screenrecord.utils.eventbus.EventMessage;
import com.dongbo.recorder.screenrecord.widget.ResizeAbleSurfaceView;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author GuoZi
 * @date :2020/5/6 21:23
 * @description: 视频变序
 */
public class SequenceActivity extends BaseActivity {
    @BindView(R.id.sequence_back)
    ImageView sequenceBack;
    @BindView(R.id.sequence_save)
    TextView sequenceSave;
    @BindView(R.id.sequence_sv)
    ResizeAbleSurfaceView sequenceSv;
    @BindView(R.id.sequence_start)
    ImageView sequenceStart;
    @BindView(R.id.sequence_rv)
    RecyclerView sequenceRv;
    @BindView(R.id.paly_logo)
    ImageView palyLogo;

    private MediaPlayer mediaPlayer;
    private String videoPath;

    private EditAdapter editAdapter;
    private List<EditVideoBean> editList = new ArrayList<>();


    @Override
    protected void onRestart() {
        super.onRestart();
        if (!TextUtils.isEmpty(videoPath)) {
            palyLogo.setVisibility(View.VISIBLE);
            Glide.with(this).load(videoPath).into(palyLogo);
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_sequence;
    }

    @Override
    protected void initView() {
        ImmersionBar.with(this).fitsSystemWindows(true).statusBarColor(R.color.white).statusBarDarkFont(true).init();
        initAdapter();
    }

    @Override
    protected void initData() {
        videoPath = getIntent().getStringExtra("videoPath");
        editList.add(new EditVideoBean("正放", videoPath));
        editList.add(new EditVideoBean("倒放", ""));
        editAdapter.setList(editList);
        editAdapter.setChoose(0);

        Glide.with(this).load(videoPath).into(palyLogo);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initListener() {
        sequenceSv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    play();
                }
                return true;
            }
        });
    }

    @OnClick({R.id.sequence_back, R.id.sequence_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.sequence_back:
                finish();
                break;
            case R.id.sequence_save:
                if (editAdapter.getChoose() == 0) {
                    showToast("暂未编辑视频无需保存");
                    return;
                }
                String path = FileUtils.getScreenRecordFile() + "0x" + System.currentTimeMillis() + ".mp4";
                if (FileUtils.getMoveFile(SequenceActivity.this, editAdapter.getItem(editAdapter.getChoose()).getPath(), path, false)) {
                    EventBusUtils.post(new EventMessage<>(Contents.EventType.TAG_RECORD_SUCCESS, true));
                    new XPopup.Builder(SequenceActivity.this).asConfirm("提示", "文件保存成功",
                            new OnConfirmListener() {
                                @Override
                                public void onConfirm() {
                                    Intent intent = new Intent(SequenceActivity.this, PlayActivity.class);
                                    intent.putExtra("videoPath", path);
                                    startActivity(intent);
                                }
                            })
                            .setCancelText("确定")
                            .setConfirmText("前往查看")
                            .show();
                } else {
                    showToast("文件保存失败");
                }
                break;
        }
    }

    private void initAdapter() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        sequenceRv.setLayoutManager(linearLayoutManager);
        if (editAdapter == null) {
            editAdapter = new EditAdapter();
            editAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                    editAdapter.setChoose(position);
                    //暂停
                    if (mediaPlayer != null) {
                        mediaPlayer.pause();
                    }
                    if (TextUtils.isEmpty(editAdapter.getItem(position).getPath())) {
                        switch (position) {
                            //正序
                            case 0:

                                break;
                            //倒叙
                            case 1:
                                if (TextUtils.isEmpty(editAdapter.getItem(position).getPath())) {
                                    StartChangeSequence();
                                }
                                break;
                        }

                    } else {
                        if (mediaPlayer != null) {
                            if (mediaPlayer.isPlaying()) {
                                mediaPlayer.stop();
                            }
                            mediaPlayer.release();
                            mediaPlayer = null;
                        }
                        play();
                    }

                }
            });
        }
        sequenceRv.setAdapter(editAdapter);
    }

    public void play() {
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
            //设置类型
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//            int width = (int) FFmpegCommand.getInfoSync(editAdapter.getItem(editAdapter.getChoose()).getPath(), Attribute.WIDTH);
//            int height = (int) FFmpegCommand.getInfoSync(editAdapter.getItem(editAdapter.getChoose()).getPath(), Attribute.HEIGHT);
//            sequenceSv.resize(width, height);
            sequenceSv.resize(1080, 1920);
            try {
                /* 为MediaPlayer 设置数据源 */
                mediaPlayer.setDataSource(editAdapter.getItem(editAdapter.getChoose()).getPath());
                /* 准备 */
                mediaPlayer.prepare();
                //将播放器捕捉的画面展示到SurfaceView画面上
                mediaPlayer.setDisplay(sequenceSv.getHolder());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            mediaPlayer.start();
            palyLogo.setVisibility(View.GONE);
            sequenceStart.setVisibility(View.GONE);
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    sequenceStart.setVisibility(View.VISIBLE);
                    palyLogo.setVisibility(View.VISIBLE);
                    Glide.with(SequenceActivity.this).load(videoPath).into(palyLogo);
                }
            });
        } else if (mediaPlayer.isPlaying()) {
            sequenceStart.setVisibility(View.VISIBLE);
            mediaPlayer.pause();
        } else {
            sequenceStart.setVisibility(View.GONE);
            palyLogo.setVisibility(View.GONE);
            mediaPlayer.setDisplay(sequenceSv.getHolder());
            mediaPlayer.start();
        }
    }

    /**
     * 开始倒叙
     */
    private void StartChangeSequence() {
        String path = FileUtils.getCacheFile() + System.currentTimeMillis() + ".mp4";
        FFmpegCommand.runAsync(FFmpegUtils.reverseVideo(videoPath, path), callback("视频倒放完成", path));
    }

    BasePopupView basePopupView;

    private CommonCallBack callback(final String msg, final String targetPath) {
        LoadingPop loadingPop = new LoadingPop(SequenceActivity.this);
        return new CommonCallBack() {
            @Override
            public void onStart() {
                basePopupView = new XPopup.Builder(SequenceActivity.this)
                        .dismissOnBackPressed(false)
                        .dismissOnTouchOutside(false)
                        .asCustom(loadingPop)
                        .show();
            }

            @Override
            public void onComplete() {
                Log.v("gstory=============>", "到这里了");
                System.out.println("到这列了");
                basePopupView.dismiss();
                if (mediaPlayer != null) {
                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.stop();
                    }
                    mediaPlayer.release();
                    mediaPlayer = null;
                }
                showToast(msg);
                editAdapter.getItem(editAdapter.getChoose()).setPath(targetPath);
                play();
            }

            @Override
            public void onCancel() {
                basePopupView.dismiss();
            }

            @Override
            public void onProgress(int progress) {
                loadingPop.setProgress(progress);
            }
        };
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                sequenceStart.setVisibility(View.VISIBLE);
                mediaPlayer.pause();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}
